package per.dg.basicusesocket;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.InterfaceAddress;
import java.net.Socket;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new Thread(new Runnable() {
            @Override
            public void run() {
                readWebpageData("www.baidu.com");
            }
        }).start();
    }

    private void readWebpageData(String host){
        int port = 80;
        InetSocketAddress inetSocketAddress = new InetSocketAddress(host, port);
        Socket socket = new Socket();
        OutputStream outputStream = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        try {
            socket.connect(inetSocketAddress);
            String strSend = "GET / HTTP/1.1\r\nHost: " + host + "\r\nConnection: Close\r\n\r\n";
            outputStream = socket.getOutputStream();
            byte[] bytes = strSend.getBytes();
            outputStream.write(bytes);
            outputStream.flush();

            inputStream = socket.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while((line = bufferedReader.readLine()) != null) {
//                System.out.println(line + "\r\n");
                Log.d(TAG, "readWebpageData: " + line);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            outputStream.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {

        }
    }
}